<template>
  <div class="common">
    <el-upload
        style="display: flex;flex-direction: row;justify-content: center;margin-bottom: 10px"
        action="https://ctba.oss-cn-shanghai.aliyuncs.com"
        accept=".mp4"
        :data="this.dataObj"
        :show-file-list="false"
        :before-upload="beforeUpload"
        :on-success="handleUploadSuccess"
        :on-progress="uploadVideoProcess"
    >
      <el-button v-if="!uploaded" size="small" type="primary">点击上传</el-button>
      <el-button v-else size="small" type="success">更换视频</el-button>
    </el-upload>
    <div v-if="progressFlag" style="width:100%;display: flex;flex-direction: row;margin-bottom: 5px;justify-content: center">
      <div>上传进度:</div>
      <!--     进度条 -->
      <el-progress style="width: 80%"
                   :text-inside="true"
                   :stroke-width="26"
                   :color="customColors"
                   :percentage="loadProgress"></el-progress>
    </div>

    <video-player v-if="uploaded" style="width: 88%;"
        class="video-player vjs-custom-skin"
        ref="videoPlayer" @canplay="onPlayerCanplay($event)"
        :options="playerOptions"/>
  </div>
</template>

<script>
import {policy, uploadVideo} from "@/api/oss";
import pubsub from 'pubsub-js'
export default {
  name:"VideoUpload",
  data(){
    return {
      customColors: [
        {color: '#f56c6c', percentage: 30},
        {color: '#1989fa', percentage: 70},
        {color: '#5cb87a', percentage: 100}
      ],
      //视频地址
      url:'',
      pubId:'',
      //视频信息
      info:{
        url:'',
        type:'',
        id:'',
      },
      uploaded:false, //是否成功上传标记
      dataObj:{
        policy: '',
        signature: '',
        key: '',
        OSSAccessKeyId: '',
        dir: '',
        host: ''
      },
      playerOptions: {
        playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: "video/mp4",// 这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
          src: "" // url地址
        }],
        poster: "", // 你的封面地址
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true  // 全屏按钮
        }
      },
      loadProgress: 0, // 动态显示进度条
      progressFlag: false, // 关闭进度条

    }
  },
  methods:{
    //视频可以播放的回调函数
    onPlayerCanplay(player){
      //发送视频长度
      pubsub.publish('duration',player.duration())
    },
    handleUploadSuccess () {
      this.info.url=this.url
      //上传视频信息
      uploadVideo(this.info).then(()=>{
        console.log("上传后")
        console.log(this.info)
        //预览视频
        this.uploaded=true
        this.playerOptions.sources[0].src=this.url
        this.playerOptions.poster=this.url+"?x-oss-process=video/snapshot,t_1000,m_fast"
      })
    },
    async beforeUpload(file){
      const isLt2G = file.size / 1024 / 1024 / 1024 < 2;
      const isVideo =['video/mp4', 'video/ogg','video/flv','video/avi','video/wmv','video/rmvb'].indexOf(file.type) !== -1;
      if (!isVideo) {
        this.$notify({
          title: 'EasyCTBA',
          message: '上传视频只能是 mp4、ogg、flv、avi、wmv、rmvb 格式！',
          type: 'error',
          duration: '3000',
          offset: 100
        });
      }
      if (!isLt2G) {
        this.$notify({
          title: 'EasyCTBA',
          message: '上传视频大小不能超过 2GB!',
          type: 'error',
          duration: '3000',
          offset: 100
        });
      }

      const filename = file.name; //文件名
      await policy().then((res)=>{
        this.dataObj.policy=res.data.policy
        this.dataObj.signature=res.data.Signature
        this.dataObj.OSSAccessKeyId=res.data.OSSAccessKeyId
        this.dataObj.key=res.data.dir+"/"+filename
        this.dataObj.dir=res.data.dir
        this.dataObj.host=res.data.host
        this.url=this.dataObj.host+"/"+this.dataObj.key
      })

      return isVideo && isLt2G ? Promise.resolve() : Promise.reject();
    },
    //进度条
    uploadVideoProcess(event) {
      this.progressFlag = true; // 显示进度条
      this.loadProgress = parseInt(event.percent); // 动态获取文件上传进度
      if (this.loadProgress >= 100) {
        this.loadProgress = 100
        setTimeout( () => {this.progressFlag = false}, 3000) // 一秒后关闭进度条
      }
    },
    //初始化组件
    initComponent(data){
      this.info=data
      if (this.info.url){
        this.playerOptions.sources[0].src=this.info.url
        this.playerOptions.poster=this.info.url+"?x-oss-process=video/snapshot,t_1000,m_fast"
        this.uploaded=true
      }
    },
  },
  mounted() {
    // this.$nextTick(function(){
    //
    // });
    this.pubId = pubsub.subscribe('initVideo', (_,data) => {
      this.initComponent(data)
    })
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    pubsub.unsubscribe(this.pubId)
  },

}
</script>

<style scoped>
.common{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;
  align-items: center;
}
</style>